package com.laboratory.report.lab04.lab0402;

import com.laboratory.report.lab04.lab0401.Lab0401Main;
import com.laboratory.report.lab04.lab0401.Medal;
import lombok.SneakyThrows;

import java.io.*;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * @author tangheng
 */
public class SerializerEvent {

    private static final URL urlRead = Lab0401Main.class.getClassLoader().getResource("event-read.txt");
    private static final URL urlWrite = Lab0401Main.class.getClassLoader().getResource("event-write.txt");
    private static final File fileRead;
    private static final File fileWrite;
    static {
        try {
            fileRead = new File(urlRead.toURI());
            fileWrite = new File(urlWrite.toURI());
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
    }

    @SneakyThrows
    public void writeToFile(Event[] events) {
        try(BufferedWriter fw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileWrite, false)))) {
            for (Event event : events) {
                fw.append(event.toLine() + "\n");
            }
        }
    }

    @SneakyThrows
    public Event[] readFromFile() {
        try(BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(fileRead)))) {
            List<Event> events = new ArrayList<>();
            String line = br.readLine();
            while(line!=null) {
                Event event = Event.fromLine(line);
                if(null != event) {
                    events.add(event);
                }
                line = br.readLine();
            }
            return events.toArray(new Event[]{});
        }
    }
}
